import Snake, { snakes } from './sanke.js';
import Bug from './bug.js';
import Play from './play.js';

class App {
  constructor(options) {
    this.$options = Object.assign(
      {
        width: 800, // 画布宽度
        height: 500, // 画布高度
        boxWidth: 50, // 格子尺寸
        box: {
          width: 50,
          height: 50,
        },
      },
      options
    );

    this.$el = this.element();
    this.box();

    // 创建小蛇
    this.snake({ bgColor: 'red', ...this.randomPosition() });
    // 创建小虫
    this.bug();
    // 动画
    new Play(this);
  }

  element() {
    const { width, box } = this.$options;
    const el = document.createElement('div');
    el.classList.add('app');
    const num = width / box.width;
    el.style.gridTemplateColumns = `repeat(${num}, ${box.width}px)`;
    el.style.gridAutoRows = box.height + 'px';
    document.body.insertAdjacentElement('beforeend', el);
    return el;
  }

  // 生成网格
  box() {
    const { width, height, box } = this.$options;
    const num = (width * height) / (box.width * box.height);
    const fragment = document.createDocumentFragment();
    Array(num)
      .fill('')
      .forEach((item) => {
        const div = document.createElement('div');
        div.classList.add('box');
        fragment.appendChild(div);
      });
    this.$el.appendChild(fragment);
  }
  // 创建小蛇
  snake(options) {
    const _snake = new Snake(this, options);
    this.$el.insertAdjacentElement('beforeend', _snake.$el);
  }
  // 创建小虫
  bug() {
    const _bug = new Bug(this, this.bugPisition());
    this.$el.insertAdjacentElement('beforeend', _bug.$el);
  }

  // 生成小虫子的坐标，不会在蛇身上
  bugPisition() {
    let position;
    while ((position = this.randomPosition())) {
      // let state = snakes.some(snake=>snake.)
      let state = snakes.forEach(
        (snake) => snake.left === position.left && snake.top === position.top
      );
      if (!state) return position;
      break;
    }
  }
  randomPosition() {
    const { width, height, box } = this.$options;
    const left = Math.floor(Math.random() * (width / box.width)) * box.width;
    const top = Math.floor(Math.random() * (height / box.height)) * box.height;
    return {
      left,
      top,
    };
  }
}

export default App;
